package com.example.list;

import org.junit.jupiter.api.Test;
import org.redisson.RedissonBlockingDeque;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.example.demo.DemoApplication;

@SpringBootTest(classes = DemoApplication.class)
public class RedisListTest {
    @Autowired
    private RedissonClient client;

    private static final String REDIS_QUEUE = "list_queue";

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisListTest.class);
    
    @Test
    public void test_redis_list_mq() throws Exception {
        RedissonBlockingDeque r;
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                producer("message" + i);
            }
        }).start();

        new Thread(() -> {
            consumer();
        }).start();

        Thread.currentThread().join();
    }

    // 消费者，阻塞
    public void consumer() {
        RBlockingDeque<String> deque = client.getBlockingDeque(REDIS_QUEUE);
        boolean isCheck = true;
        while (isCheck) {
            try {
                String message = deque.takeLast();
                System.out.println("consumer: " + message);
            } catch (InterruptedException e) {
                LOGGER.error("consumer failed, cause: {}", e.getMessage());
            }
        }
    }


    // 生产者
    public void producer(String message) {
        RBlockingDeque<String> deque = client.getBlockingDeque(REDIS_QUEUE);
        System.out.println(deque.getClass());
        try {
            deque.putFirst(message);
        } catch (InterruptedException e) {
            LOGGER.error("producer failed, msg: {}, cause: {}", message, e.getMessage());
        }
    }
}
